package com.hm.service.impl.task;

import com.hm.service.entity.ydcg.TaskDetailsBean;
import com.hm.service.service.main.CronExpressionService;
import com.hm.service.service.main.TaskDetailsService;
import com.hm.service.service.main.TaskHandleService;
import com.hm.service.framework.base.BaseServiceImpl;
import com.hm.service.impl.task.help.TaskMap;
import com.hm.service.impl.task.help.TaskUtils;
import com.hm.service.task.PushHandleCaseJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 定时任务实现类
 */
@Service
public class TaskHandleServiceImpl extends BaseServiceImpl implements TaskHandleService {

    private static final Logger logger = LoggerFactory.getLogger(TaskHandleServiceImpl.class);

    @Qualifier("StdSchedulerFactory")
    private final SchedulerFactoryBean stdSchedulerFactory;

    private final CronExpressionService cronExpressionService;

    private final TaskDetailsService taskDetailsService;

    public TaskHandleServiceImpl(TaskDetailsService taskDetailsService, SchedulerFactoryBean stdSchedulerFactory, CronExpressionService cronExpressionService) {
        this.stdSchedulerFactory = stdSchedulerFactory;
        this.cronExpressionService = cronExpressionService;
        this.taskDetailsService = taskDetailsService;
    }

    @Override
    public void startTaskForPersistence() {
        try {
            //程序启动可以从数据库中拿到未完成的job继续执行
            Scheduler scheduler = stdSchedulerFactory.getScheduler();
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String startTask(String taskId, String cronId, String description) {
        try {
            // job详情，描述job的执行类，job的名称，组等
            Scheduler scheduler = stdSchedulerFactory.getScheduler();
            JobKey jobKey = TaskMap.jobKeyMap.get(taskId);
            TriggerKey triggerKey = TaskMap.triggerKeyMap.get(taskId);
            JobDetail jobDetail1 = scheduler.getJobDetail(jobKey);
            if (jobDetail1 != null) {
                return generateFail("有重复任务");
            }
            switch (taskId) {
                case "100001":
                    String cron = cronExpressionService.getCronExpression(cronId);
                    JobDetail jobDetail = TaskUtils.generateJobDetail(jobKey, PushHandleCaseJob.class);
                    Trigger trigger = TaskUtils.generateTrigger(triggerKey, cron);
                    scheduler.scheduleJob(jobDetail, trigger);
                    //保存任务信息
                    taskDetailsService.saveTask(taskId, jobKey.toString(), PushHandleCaseJob.class.getName(), cron, "运行中", description);
                    return generateSucceed("任务号：" + taskId + "启动成功");

                case "100002":
                    break;

                default:
                    return generateFail("无效的任务号");
            }
            return generateFail("启动失败");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public String deleteTask(String taskId) {
        try {
            Scheduler scheduler = stdSchedulerFactory.getScheduler();
            // 获取现有的JobDetail
            JobKey jobKey = TaskMap.jobKeyMap.get(taskId);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return generateFail("该任务不存在！");
            }
            scheduler.pauseJob(jobKey);//暂停
            scheduler.deleteJob(jobKey);//删除
            taskDetailsService.deleteTask(taskId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return generateSucceed("任务号：" + taskId + "已停止");
    }

    @Override
    public String editTask(String taskId, String cronId) {
        try {
            Scheduler scheduler = stdSchedulerFactory.getScheduler();
            // 获取现有的JobDetail
            JobKey jobKey = TaskMap.jobKeyMap.get(taskId);
            TriggerKey triggerKey = TaskMap.triggerKeyMap.get(taskId);
            //判断有无该jobDetail
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail == null) {
                return generateFail("该任务不存在！");
            }
            // 创建一个新的CronTrigger
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            String oldCronExpression = cronTrigger.getCronExpression();//拿到旧cron表达式
            String cronExpression = cronExpressionService.getCronExpression(cronId);
            if (oldCronExpression.equals(cronExpression)) {
                return generateFail("该任务触发时间一样");
            }
            //更新任务信息
            taskDetailsService.updateTask(taskId, cronExpression);
            Trigger trigger = TaskUtils.generateTrigger(triggerKey, cronExpression);
            scheduler.rescheduleJob(trigger.getKey(), trigger);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return generateSucceed("任务号：" + taskId + "修改成功");
    }

    @Override
    public String queryAllTask() {
        try {
            List<TaskDetailsBean> taskDetailsBeans = taskDetailsService.queryAllTask();
            return generateSucceed(taskDetailsBeans);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
